package com.wn.search.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.wn.common.model.ArticleList
import com.wn.common.provider.MainServiceProvider
import com.wn.framework.adapter.BaseBindViewHolder
import com.wn.framework.adapter.BaseRecyclerViewAdapter
import com.wn.search.databinding.LayoutSearchResultItemBinding
import dagger.hilt.android.qualifiers.ActivityContext
import dagger.hilt.android.scopes.ActivityScoped
import javax.inject.Inject

/**
 * @Author: wn
 * @Date: 2024/12/13 17:18
 * @Description: 搜索结果适配器
 */
@ActivityScoped
class SearchResultAdapter @Inject constructor(@ActivityContext private val context: Context) :
  BaseRecyclerViewAdapter<ArticleList.ArticleInfo, LayoutSearchResultItemBinding>() {
  /**
   * 点击 收藏按钮 触发
   */
  var onClickCollect: ((position: Int, item: ArticleList.ArticleInfo) -> Unit)? = null

  /**
   * 子类通过 xml实现 ViewBinding，父类提供了 LayoutInflater ，viewType
   * 可以根据不同的 viewType传递不同的 viewBinding -- when
   */
  override fun getViewBinding(
    layoutInflater: LayoutInflater,
    parent: ViewGroup,
    viewType: Int,
  ): LayoutSearchResultItemBinding =
    LayoutSearchResultItemBinding.inflate(layoutInflater, parent, false)

  /**
   * 子类重写该方法绑定数据
   * 重写 [getViewBinding] 即可实现不同ViewHolder传递
   */
  override fun setViewBinding(
    holder: BaseBindViewHolder<LayoutSearchResultItemBinding>,
    item: ArticleList.ArticleInfo?,
    position: Int,
  ) {
    item?.apply {
      // 传递 data 给 xml
      holder.binding.item = this
      // 点击整个 Item 去详情页
      holder.itemView.setOnClickListener {
        if (this.link.isNullOrEmpty()) return@setOnClickListener
        MainServiceProvider.toArticleDetail(context, this.link!!, this.title ?: "")
      }
      // 点击收藏按钮
      holder.binding.ivCollect.setOnClickListener {
        onClickCollect?.invoke(position, this)
      }
    }
  }
}